package com.cloud.service.impl;

import com.cloud.dao.ReagentResultDao;
import com.cloud.domain.LoginUser;
import com.cloud.pojo.ReagentResult;
import com.cloud.service.ReagentResultService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Author: Tangtao
 * @Date: 2022/4/20 18:57
 * @Description: Nucleic acid results service implementation class
 * @ClassName: ReagentResultServiceImpl
 */
@Service
public class ReagentResultServiceImpl implements ReagentResultService {
    @Resource
    private ReagentResultDao reagentResultDao;

    @Override
    public List<ReagentResult> checkTestResultById() {
        String cardId = getUserIdFromToken();
        List<String> bottleId = reagentResultDao.getBottleIdByCardId(cardId);
        List<ReagentResult> results = new ArrayList<>();
        for (String id : bottleId){
            results.add(reagentResultDao.checkTestResultByBottleId(id));
        }
        return results;
    }

    @Override
    public boolean saveTestResultOnce(ReagentResult reagentResult) {
        return reagentResultDao.saveTestResult(reagentResult) == 1;
    }

    @Override
    public boolean saveTestResultBatch(List<ReagentResult> reagentResultList) {
        int resultInt = 0;
        for (ReagentResult reagentResult: reagentResultList) {
            resultInt += reagentResultDao.saveTestResult(reagentResult);
        }
        return resultInt == reagentResultList.size();
    }

    @Override
    public boolean resultManage(ReagentResult reagentResult) {
        return reagentResultDao.resultUpdate(reagentResult) == 1;
    }

    @Override
    public List<ReagentResult> getResultByIdForManager(Map<String,String> map) {
        String cardId = map.get("userId");
        List<ReagentResult> results = new ArrayList<>();
        List<String> bottleId = reagentResultDao.getBottleIdByCardId(cardId);
        for (String id : bottleId){
            results.add(reagentResultDao.checkTestResultByBottleId(id));
        }
        return results;
    }

    @Override
    public List<ReagentResult> getAllResult() {
        return reagentResultDao.getAllResult();
    }

    @Override
    public boolean deleteResult(String bottleId) {
        return reagentResultDao.deleteResult(bottleId) == 1;
    }

    public static String getUserIdFromToken(){
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return loginUser.getUser().getUserId();
    }
}
